package com.esd.crm.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 入口界面，登录
 * 
 * @author snailzhang
 *
 */
@Controller
public class IndexController {

	private static final Logger logger = LogManager.getLogger(IndexController.class);

	@Value("${spring.datasource.url}")
	private String SPRING_DATASOURCE_URL;

	@RequestMapping(value = "/sdu", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> getSDU() {
		String v="";
		Map<String, Object> map = new HashMap<String, Object>();
		String[] split=SPRING_DATASOURCE_URL.split("\\?");
		if(split.length>0) {
			int start=split[0].lastIndexOf("/");
			if(start!=-1) {
				v=split[0].substring(start+1, split[0].length());
			}
		}
		map.put("sdu", v);
		return map;
	}
	/**
	 * 测试更换数据库链接
	 * 
	 * @return
	 */
	@RequestMapping(value = "/cb", method = RequestMethod.GET)
	public ModelAndView changLinkDBGet(HttpServletRequest request) {

		String webapp = request.getSession().getServletContext().getRealPath("\\");
		System.out.println(webapp);
		String app = webapp + "\\WEB-INF\\classes\\application.properties";
		// System.out.println("webapp:" + webapp);
		// System.out.println(app);
		// String ss =
		// "C:\\Users\\snailzhang\\git\\LFCRM\\src\\main\\resources\\application.properties";
		// readFileByLines(app);
		// modifyFileContent();
		String ss = "C:\\Users\\snailzhang\\git\\LFCRM\\src\\main\\resources\\application.properties";
		String s1 = "jdbc:mysql://127.0.0.1:3306/crm2019?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false";
		String s2 = "jdbc:mysql://127.0.0.1:3306/crm2020?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false";
		modifyFileContent(app, s1, s2);
		return null;
	}

	public static void main(String[] args) {

		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			// 一开始必须填一个已经存在的数据库
			String url = "jdbc:mysql://127.0.0.1:3306/crm2019?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false";
			Connection conn = DriverManager.getConnection(url, "root", "esd123");
			Statement stat = conn.createStatement();
			// 创建数据库hello
			stat.executeUpdate("create database hello");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// String ss =
		// "C:\\Users\\snailzhang\\git\\LFCRM\\src\\main\\resources\\application.properties";
		// String s1 =
		// "jdbc:mysql://127.0.0.1:3306/crm2019?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false";
		// String s2 =
		// "jdbc:mysql://127.0.0.1:3306/crm2020?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false";
		// modifyFileContent(ss, s2, s1);
	}

	/**
	 * 修改文件内容
	 * 
	 * @param fileName
	 * @param oldstr
	 * @param newStr
	 * @return
	 */
	private static boolean modifyFileContent(String fileName, String oldstr, String newStr) {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile(fileName, "rw");
			String line = null;
			long lastPoint = 0; // 记住上一次的偏移量
			while ((line = raf.readLine()) != null) {
				final long ponit = raf.getFilePointer();
				if (line.contains(oldstr)) {
					String str = line.replace(oldstr, newStr);
					raf.seek(lastPoint);
					raf.writeBytes(str);
				}
				lastPoint = ponit;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				raf.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return true;
	}

	public StringBuffer readFileByLines(String fileName) {
		StringBuffer sb = new StringBuffer();
		File file = new File(fileName);
		BufferedReader reader = null;
		try {
			System.out.println("以行为单位读取文件内容，一次读一整行：");
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			int line = 1;
			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				sb.append(tempString);
				// 显示行号
				System.out.println("line " + line + ": " + tempString);
				line++;
			}
			reader.close();
			return sb;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
		return sb;

	}

}
